<template>
  <div id="catalogue_detail">
    <!-- 返回按钮 -->
    <ReturnPage style="margin-bottom: 10px" />
    <div class="tab_box">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 属性 -->
        <el-tab-pane style="padding-bottom: 20px" label="属性" name="first">
          <div class="only_name" v-if="getExampleObj.length == 0">
            实例名:
            <!-- 属性值 -->
            <div class="value_box">
              &nbsp;&nbsp;{{ exampleDetails.model_example_name }}
              <svg-icon iconClass="icon-edit" class="editBtn" style="margin-left: 5px"
                @click="activeExample = exampleDetails.model_example_name"></svg-icon>
            </div>
            <!-- 输入框 -->
            <div class="input_box" :class="{
              active: activeExample == exampleDetails.model_example_name,
            }">
              <el-input size="mini" v-model="form.input"
                :placeholder="'请输入' + exampleDetails.model_example_name"></el-input>

              <el-button icon="el-icon-check" size="mini" circle style="margin-left: 10px"
                @click="editExample('model_example_name')"></el-button>
              <el-button icon="el-icon-close" size="mini" circle @click="activeExample = ''"></el-button>
            </div>
          </div>
          <div v-else v-for="(item, index) in getExampleObj" :key="index">
            <p style="padding-left: 10px; border-left: 5px solid #c3cdd7">
              {{ item.categoryName }}
            </p>
            <div class="stats">
              <div class="property" v-for="ele in item.children" :key="ele.modelFieldId">
                <div class="comment_box">
                  {{ ele.comment }}:
                  <!-- 属性值 -->
                  <div class="value_box">
                    &nbsp;&nbsp;{{ ele.value }}
                    <svg-icon iconClass="icon-edit" class="editBtn" style="margin-left: 5px"
                      @click="activeExample = ele.newFieldName; form.input = ele.value"></svg-icon>
                  </div>
                  <!-- 输入框 -->
                  <div class="input_box" v-if="activeExample == ele.newFieldName">
                    <!-- <el-date-picker v-if="ele.type == 'DATE'" v-model="input" type="date"
                      :placeholder="'请选择' + ele.comment" value-format="yyyy-MM-dd">
                    </el-date-picker>

                    <el-date-picker v-else-if="ele.type == 'DATETIME'" v-model="input" type="datetime"
                      value-format="yyyy-MM-dd HH:mm:ss" :placeholder="'请选择' + ele.comment">
                    </el-date-picker> -->
                    <el-form :model="form" ref="form">
                      <el-form-item prop="input" :rules="rules[ele.newFieldName]">
                        <el-input size="mini" v-model="form.input" :placeholder="'请输入' + ele.comment"></el-input>
                        <el-button icon="el-icon-check" size="mini" circle style="margin-left: 10px"
                          @click="editExample('form', ele.newFieldName)"></el-button>
                        <el-button icon="el-icon-close" size="mini" circle @click="activeExample = ''"></el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <!-- 关联 -->
        <!-- <el-tab-pane label="关联" name="second">
          <div style="display: flex; justify-content: space-between">
            <el-button type="primary" size="mini">新增关联</el-button>
            <div>
              <el-checkbox v-model="checked" size="mini">全部展开</el-checkbox>
              <el-radio-group
                size="mini"
                v-model="activeRadio"
                style="margin-left: 15px"
              >
                <el-radio-button label="列表">列表</el-radio-button>
                <el-radio-button label="拓扑">拓扑</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="relevance" v-if="associationTableData.length == 0">
            暂无关联关系
          </div>
          <el-collapse v-else v-model="associationActiveName" accordion>
            <el-collapse-item
              class="mt10"
              v-for="item in associationTableData"
              :key="item.id"
            >
              <template slot="title">
                <div class="title_text">
                  {{ item.name
                  }}<span>&nbsp;&nbsp;({{ item.children.length }})</span>
                </div>
              </template>
              <div>
                <el-table :data="item.children" size="mini">
                  <el-table-column prop="INSIDE_IP" label="内网IP">
                  </el-table-column>
                  <el-table-column prop="OUTSIDE_IP" label="外网IP">
                  </el-table-column>
                  <el-table-column prop="service" label="主要维护人">
                  </el-table-column>
                  <el-table-column prop="service2" label="备份维护人">
                  </el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="primary"
                        @click="handleEdit(scope.$index, scope.row)"
                        >取消关联</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane> -->
        <!-- 变更记录 -->
        <!-- <el-tab-pane label="变更记录" name="third">
          <el-date-picker
            style="width: 300px"
            v-model="date"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
          >
          </el-date-picker>
          <el-input
            style="width: 200px; margin-left: 20px"
            v-model="searchVal"
            placeholder="操作账号"
            clearable
            size="small"
            suffix-icon="el-icon-search"
            @keyup.enter.native="search"
          >
          </el-input>
          <el-table
            style="border: 1px solid #dfe6ec; margin-top: 10px"
            v-loading="loading"
            :data="tableData"
            :header-cell-style="{ backhround: '#eee' }"
            height="calc(100vh - 300px)"
          >
            <el-table-column
              label="操作描述"
              align="left"
              prop="description"
            ></el-table-column>
            <el-table-column label="操作账号" align="left" prop="account" />
            <el-table-column
              label="操作时间"
              align="left"
              prop="time"
            ></el-table-column>
          </el-table>
        </el-tab-pane> -->
      </el-tabs>
    </div>
  </div>
</template>

<script>
let queryIp = (rule, value, callback) => {
  const ipv4Regex =
    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?::[0-9]{1,5})?$/;
  if (!ipv4Regex.test(value)) {
    callback(new Error("ip格式错误"));
  } else {
    callback();
  }
};
import {
  getModelExampleDetail_Api, //根据实例id查询实例详情
  getModelIdCategoryList_Api, //根据模型id查询模型分组列表
  editModelExample_Api, //编辑模型实例
  getAssociationList_Api, //根据modelId查询模型关联列表
} from "@/api/configuration/resource.js";

export default {
  data() {
    return {
      rules: {
        model_example_name: [
          { required: true, message: `请输入实例名`, trigger: "blur" },
        ],
      },
      activeName: "first", //选中的tab
      checked: false, //全部展开选择框
      activeRadio: "列表", //选中的radio
      date: "", //日期
      searchVal: "", //搜索
      loading: false, //变更记录列表loading
      //变更记录列表数据
      tableData: [
        {
          description: "新增实例",
          account: "admin",
          time: "2023/08/09 14:20:12",
        },
        {
          description: "修改实例",
          account: "admin",
          time: "2023/08/09 14:20:12",
        },
        {
          description: "修改实例",
          account: "admin",
          time: "2023/08/09 14:20:12",
        },
        {
          description: "新增实例",
          account: "admin",
          time: "2023/08/09 14:20:12",
        },
        {
          description: "新增实例",
          account: "admin",
          time: "2023/08/09 14:20:12",
        },
        {
          description: "删除实例",
          account: "admin",
          time: "2023/08/09 14:20:12",
        },
        {
          description: "新增实例",
          account: "admin",
          time: "2023/08/09 14:20:12",
        },
        {
          description: "新增实例",
          account: "admin",
          time: "2023/08/09 14:20:12",
        },
        {
          description: "新增实例",
          account: "admin",
          time: "2023/08/09 14:20:12",
        },
      ],
      //实例属性字段
      exampleFields: [],
      //实例属性详情
      exampleDetails: {},
      form: {
        input: "", //编辑字段输入的值
      },
      activeExample: "", //选中的字段
      //关联表格数据
      associationTableData: [
        {
          id: "1",
          name: "上联-主机",
          children: [
            {
              id: "1-1",
              INSIDE_IP: "2442.42.242.242",
              OUTSIDE_IP: "2442.42.242.242",
              service: "admin",
              service2: "--",
              num: "T--",
            },
            {
              id: "1-2",
              INSIDE_IP: "2442.42.242.242",
              OUTSIDE_IP: "2442.42.242.242",
              service: "admin",
              service2: "--",
              num: "T--",
            },
          ],
        },
        {
          id: "2",
          name: "属于-主机",
          children: [
            {
              id: "2-1",
              INSIDE_IP: "2442.42.242.242",
              OUTSIDE_IP: "2442.42.242.242",
              service: "admin",
              service2: "--",
              num: "T--",
            },
          ],
        },
      ],
      associationActiveName: "", //关联列表选中
    };
  },
  created() {
    //获取实例详情字段信息
    this.getExampleFields(this.$route.query.modelId);
    //获取实例详情数据
    this.getExampleData(this.$route.query.exampleId);
    //获取模型关联列表
    // this.getAssociationData();
  },
  methods: {
    //根据实例id获取实例详情数据
    getExampleData(id) {
      getModelExampleDetail_Api(id).then((res) => {
        res.data.forEach(
          (item) => (this.exampleDetails = { ...this.exampleDetails, ...item })
        );
      });
    },
    //根据modelId获取实例详情字段信息
    getExampleFields(id) {
      //查询字段
      getModelIdCategoryList_Api({ modelId: id }).then((res) => {
        this.exampleFields = res.data;
      });
    },
    //编辑模型实例的方法
    //必选参数：实例id + 模型id + （要修改的字段（newFieldName）和新值）
    editExample(formName, newFieldName) {
      this.$refs[formName][0].validate((valid) => {
        if (valid) {
          if (this.form.input != "") {
            editModelExample_Api({
              // modelId: this.$route.query.modelId,
              // modelExampleId: this.$route.query.exampleId,
              ...this.exampleDetails,
              [newFieldName]: this.form.input,
            })
              .then((res) => {
                this.getExampleData(this.$route.query.exampleId);
                this.$message.success("修改成功");
                this.activeExample = "";
                this.form.input = "";
              })
              .catch((error) => { });
          } else this.$message.info("输入不能为空");
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    //根据modelId查询模型关联列表
    // getAssociationData() {
    //   getAssociationList_Api(this.$route.query.modelId).then((res) => {
    //     // console.log(res);
    //   });
    // },
    //切换tab
    handleClick(tab, event) { },
    //搜索
    search() { },
  },
  computed: {
    getExampleObj() {
      //渲染的数组
      const tempArr = [];
      this.exampleFields.forEach((item) => {
        const tempCategoryObj = {};
        tempCategoryObj.categoryName = item.categoryName;
        tempCategoryObj.children = [];
        item.cgModelFields.forEach((ele) => {
          //每个字段对象
          const tempObj = {};
          tempObj.type = ele.type;
          tempObj.comment = ele.comment;
          if (ele.testingRegulationsJSON) {
            let arr = []
            JSON.parse(ele.testingRegulationsJSON).forEach(e => {
              let obj = {}
              switch (e.type) {
                case "max":
                  obj.max = Number(e.val)
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                case "min":
                  obj.min = Number(e.val)
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                case "number":
                  obj.type = e.type
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                case "string":
                  obj.type = e.type
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                case "ip":
                  obj.validator = queryIp
                  obj.trigger = e.trigger
                  break;
                case "email":
                  obj.type = e.type
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                case "required":
                  obj.required = true
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                default:
                  break;
              }
              arr.push(obj)
            })
            this.rules[ele.newFieldName] = arr
            console.log(this.rules);
          }
          //把驼峰命名转化为下划线隔开
          // const newFieldName = ele.newFieldName
          //   .replace(/([a-z])([A-Z])/g, "$1_$2")
          //   .toLowerCase();
          // tempObj.newFieldName = newFieldName;
          tempObj.newFieldName = ele.newFieldName;
          tempObj.value = this.exampleDetails[ele.newFieldName];
          tempObj.edit_box_visible = false; //控制编辑输入框显示隐藏

          tempCategoryObj.children.push(tempObj);
        });
        if (tempArr.length == 0) {
          tempCategoryObj.children.unshift({
            comment: "实例名",
            value: this.exampleDetails.model_example_name,
            edit_box_visible: false,
            newFieldName: "model_example_name",
            type: "TEXT",
          });
        }

        tempArr.push(tempCategoryObj);
      });
      return tempArr;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-tab-pane {
  height: calc(100vh - 80px);
}

#catalogue_detail {
  .tab_box {
    background-color: #ffffff;
    border-radius: 5px;
    box-sizing: border-box;
    padding: 10px;
    height: calc(100vh - 160px);

    //只有实例名没有分组等信息时
    .only_name {
      margin-top: 20px;
      width: 200px;
      text-align: right;
      position: relative;

      .input_box {
        white-space: nowrap;
        position: absolute;
        left: 200px;
        top: -4px;
        margin-left: 5px;
        width: 200px;
        margin-right: 10px;
        z-index: 3;
        // display: none;

        &.active {
          display: block;
        }
      }

      .value_box {
        text-align: left;
        width: 350px;
        position: absolute;
        left: 200px;
        top: 2px;
        z-index: 2;
      }
    }

    //属性
    .stats {
      margin-top: 10px;
      font-size: 12px;
      display: grid;
      grid-template-columns: 48% 52%;
      gap: 20px 15px;

      .property {
        .comment_box {
          width: 200px;
          text-align: right;
          position: relative;

          .input_box {
            white-space: nowrap;
            position: absolute;
            left: 200px;
            top: -5px;
            margin-left: 5px;
            width: 200px;
            margin-right: 10px;
            z-index: 3;
            // display: none;

            &.active {
              display: block;
            }
          }

          .value_box {
            text-align: left;
            width: 350px;
            position: absolute;
            left: 200px;
            top: 0px;
            z-index: 2;
          }
        }

        &:hover .editBtn {
          display: inline-block;
          cursor: pointer;
          color: #72767c;

          &:hover {
            color: #409eff;
          }
        }

        .editBtn {
          display: none;
        }
      }
    }

    //关联
    .relevance {
      margin-top: 20%;
      text-align: center;
      color: #63656e;
    }
  }
}

//.el-collapse
::v-deep .el-collapse .el-collapse-item>div:first-child {
  height: 30px;

  .el-collapse-item__header {
    background-color: #dcdee5;
    border-radius: 3px;
    height: 30px;
    position: relative;

    .title_text {
      height: 30px;
      line-height: 30px;
      padding-left: 15px;

      span {
        color: #95979f;
        font-size: 11px;
      }
    }

    .right_text {
      position: absolute;
      right: 30px;
      font-size: 11px;
    }
  }
}

::v-deep .el-collapse .el-collapse-item .el-collapse-item__wrap .el-collapse-item__content {
  padding-bottom: 0px;
}

::v-deep .el-collapse {
  border: none;
}
</style>
